﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SonCa.SocialNetwork.Web.Friends.IPresenters;
using System.ComponentModel.Composition;
using Core.Interfaces;
using Core.BusinessLogic.Interfaces;
using Core.Common;
using SonCa.SocialNetwork.Web.HelperClass;
using Core.DataAccess;

namespace SonCa.SocialNetwork.Web.Friends.Presenters
{
    public class FriendsRequestPresenter
    {
        private IFriendsRequestPresenter _view;
        private List<FriendRequestHelper> _frienRequestHelper;
        [Import]
        private IUserSession _userSession;
        [Import]
        private IFriendInvitationService _friendInvitationService;
        [Import]
        private IAccountService _accountService;
        [Import]
        private IMessageService _messageService;

        public void Init(IFriendsRequestPresenter view)
        {
            _view = view;
            MEFManager.Compose(this);
            _frienRequestHelper = new List<FriendRequestHelper>();
            _accountService.GetAccountsByAccountIDList(_friendInvitationService.GetFriendsInvitationIDByBecameID(_userSession.CurrentUser.AccountID)).ForEach(n => _frienRequestHelper.Add(new FriendRequestHelper
            {
                AccountID = n.AccountID,
                FullName = n.FirstName,
                ImageUrl = string.Format("../Images/ProfileAvatar/ProfileImage.aspx?AccountID={0}", n.AccountID)
            }));
            List<FriendRequestHelper> lstMessage = LoadMessage();
            _view.LoadFriendRequest(_frienRequestHelper,lstMessage);
        }

        public List<FriendRequestHelper> LoadMessage()
        {
            List<FriendRequestHelper> _friendRequest = new List<FriendRequestHelper>();
            List<Message> lstMessages = _messageService.GetMessagesByAccountID(_userSession.CurrentUser.AccountID);
            if (lstMessages.Count > 0)
            {                
                foreach (Message msg in lstMessages)
                {
                    Account account = _accountService.GetAccountByID(Convert.ToInt32(msg.FriendAccountID));
                    _friendRequest.Add(new FriendRequestHelper 
                    { 
                        AccountID = account.AccountID,
                        FullName =  account.LastName + " " + account.MidName + " " + account.FirstName,
                        ImageUrl = string.Format("../Images/ProfileAvatar/ProfileImage.aspx?AccountID={0}", account.AccountID)
                    });
                    if (msg.IsRead == false)
                        _messageService.UpdateMessageIsRead(msg);
                }                
            }
            return _friendRequest;
        }
    }
}